{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 百度AI开放平台"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 本周主要内容：通用物体和场景识别（认知服务）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 接口描述"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> 该请求用于通用物体及场景识别，即对于输入的一张图片（可正常解码，且长宽比适宜），输出图片中的多个物体及场景标签。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 请求示例"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> HTTP 方法：POST"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 请求URL"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 鉴权认证机制(access_token)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 获取Access Token"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 调用方式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.69debd36fd86870ec01ad6dc22cde237.315360000.1965697332.282335-26002605', 'expires_in': 2592000, 'session_key': '9mzdXREotvUs4HGHMybxwLxnnFMJCbVXTvqOZenwp30GTwKiRPqWAh2/TLUDcaPW/H8wLBRMVUx6BNd5ZWnn0Ov3XUt/cA==', 'access_token': '24.fe478b1672af16e6d15e2cf8e9937094.2592000.1652929332.282335-26002605', 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '5abd7405768b7e25ebf4aa79b23b8275'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token? '\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'kIuMdkxyMh41sSIaDHv3zyof',\n",
    "    'client_secret':'hXLIFwAFfwIit90X8gPxMUqW54uEoW0z'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'refresh_token': '25.69debd36fd86870ec01ad6dc22cde237.315360000.1965697332.282335-26002605',\n",
       " 'expires_in': 2592000,\n",
       " 'session_key': '9mzdXREotvUs4HGHMybxwLxnnFMJCbVXTvqOZenwp30GTwKiRPqWAh2/TLUDcaPW/H8wLBRMVUx6BNd5ZWnn0Ov3XUt/cA==',\n",
       " 'access_token': '24.fe478b1672af16e6d15e2cf8e9937094.2592000.1652929332.282335-26002605',\n",
       " 'scope': 'public vis-classify_dishes vis-classify_car brain_all_scope vis-classify_animal vis-classify_plant brain_object_detect brain_realtime_logo brain_dish_detect brain_car_detect brain_animal_classify brain_plant_classify brain_ingredient brain_advanced_general_classify brain_custom_dish brain_poi_recognize brain_vehicle_detect brain_redwine brain_currency brain_vehicle_damage brain_multi_ object_detect wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx',\n",
       " 'session_secret': '5abd7405768b7e25ebf4aa79b23b8275'}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "response.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 用字典的取值方式\n",
    "Sxylm_AI2 = response.json( )['access_token']"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "* 请求参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.植物识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'keyword': '五爪金龙', 'score': 0.807123, 'root': '植物-旋花科', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E4%BA%94%E7%88%AA%E9%87%91%E9%BE%99/79188', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/267f9e2f07082838d4d8a842b599a9014d08f18b', 'description': '五爪金龙(学名：Ipomoea cairica (L.) Sweet)是管状花目、旋花科、番薯属多年生缠绕草本植物，全体无毛，茎细长，有细棱，叶片掌状，裂片卵状披针形、卵形或椭圆形，中裂片较大，聚伞花序腋生，苞片及小苞片均小，鳞片状，早落；萼片边缘干膜质，花冠紫红色、紫色或淡红色、偶有白色，漏斗状，子房无毛，花柱纤细，蒴果近球形，种子黑色，边缘被褐色柔毛。该种原产于非洲(博茨瓦纳，佛得角，埃及，厄立特里亚，埃塞俄比亚，肯尼亚，马拉维，莫桑比克，索马里，南非，斯威士兰，赞比亚和津巴布韦)和亚洲(印度，印度尼西亚，以色列，日本，约旦，巴基斯坦， 巴布亚新几内亚，菲律宾，中国南部，斯里兰卡，台湾，泰国，越南和也门)，这些地区通常靠近海滩或水流沿岸。分布于中国台湾、福建、广东及其沿海岛屿、广西、云南。生于海拔90-610米的平地或山地路边灌丛，生长于向阳处。该种通常作观赏植物栽培。块根供药用，外敷热毒疮，有清热解毒之效。广西用叶治痈疮，果治跌打。(概述图参考来源：中国自然标本馆)'}}, {'keyword': '牵牛花', 'score': 0.638474, 'root': '植物-其它', 'baike_info': {}}, {'keyword': '花卉', 'score': 0.416657, 'root': '商品-农用物资', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%8A%B1%E5%8D%89/229536', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/d6ca7bcb0a46f21fbf3a5f2bf9246b600c33aebf', 'description': '花卉，是具有观赏价值的草本植物，是用来描绘欣赏的植物的统称，喜阳且耐寒，具有繁殖功能的短枝，有许多种类。典型的花，在一个有限生长的短轴上，着生花萼、花瓣和产生生殖细胞的雄蕊与雌蕊。花由花冠、花萼、花托、花蕊组成，有各种各样的颜色，长得也各种各样，有香味或无香味等。'}}, {'keyword': '旋花', 'score': 0.246445, 'root': '植物-旋花科', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%AF%B1%E6%89%93%E7%A2%97%E8%8A%B1/2329839', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/b3f6cea2712bee8dcaefd025', 'description': '发生与危害：多年生蔓性草本。根芽和种子繁殖。3～4月份出苗，花期5～7月份，果期6～8月份。农田杂草，危害小麦及棉花，有时形成单优种群。采制： 春、秋季采收。晒干或鲜用。'}}, {'keyword': '荷花', 'score': 0.079241, 'root': '植物-其它', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%8D%B7%E8%8A%B1/158674', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/bd315c6034a85edf8db1f8f0181b1e23dd54574edf9b', 'description': '荷花(学名：Nelumbo SP.；英文名称：Lotus flower)：属毛茛目、莲科，是莲属二种植物的通称。又名莲花、水芙蓉等。是莲属多年生水生草本花卉。地下茎长而肥厚，有长节，叶盾圆形。花期6至9月，单生于花梗顶端，花瓣多数，嵌生在花托穴内，有红、粉红、白、紫等色，或有彩纹、镶边。坚果椭圆形，种子卵形。荷花种类很多，分观赏和食用两大类。原产亚洲热带和温带地区，中国早在周朝就有栽培记载。荷花全身皆宝，藕,莲子能食用，莲子、根茎、藕节、荷叶、花及种子的胚芽等都可入药。其出污泥而不染之品格恒为世人称颂。“接天莲叶无穷碧，映日荷花别样红”就是对荷花之美的真实写照。荷花“中通外直，不蔓不枝，出淤泥而不染，濯清涟而不妖”的高尚品格，历来为诗人墨客歌咏绘画的题材之一。1985年5月荷花被评为中国十大名花之一。荷花是印度、越南,马拉维的国花，也是中国山东济南市、济宁市；湖北孝感市、洪湖市；河南许昌市；广东肇庆市；江西九江市等7市的市花。(概述图参考来源：)'}}], 'log_id': 1516250818169630998}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用物体和场景识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('植物识别图.jpeg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload ={\n",
    "    'access_token':Sxylm_AI2,\n",
    "    'image':img,\n",
    "    'baike_num':5\n",
    "} \n",
    "    \n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.菜品识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result_num': 5, 'result': [{'name': '宫保鸡丁', 'calorie': '197', 'probability': '0.490111', 'baike_info': {}, 'has_calorie': True}, {'name': '虾球', 'calorie': '91', 'probability': '0.413576', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%99%BE%E7%90%83/521949', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/8640bf8bb14ced339f2fb44c', 'description': '虾球是湖北武汉的特色小吃，是大排档的特色菜肴。小龙虾去掉含内脏的上半身，用余下卷曲如球的下半身，放姜、蒜、辣椒、花椒、葱等暴炒后，外壳焦红，肉质雪白，鲜嫩可口，绝对是色、香、味全。虾皮有镇静作用，常用来治疗神经衰弱，植物神经功能紊乱诸症。'}, 'has_calorie': True}, {'name': '豆腐虾', 'calorie': '181', 'probability': '0.035266', 'baike_info': {}, 'has_calorie': True}, {'name': '咕咾肉', 'calorie': '149', 'probability': '0.0192269', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%92%95%E5%92%BE%E8%82%89/677632', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/09fa513d269759ee87ad3987bffb43166c22dff9', 'description': '咕咾肉又称咕噜肉，是广东的一道特色传统名菜，属于粤菜，以甜酸汁及猪肉煮成。咕咾肉作为欧美人士最熟悉的中国菜之一，常见于中国以外的唐人街的餐馆。'}, 'has_calorie': True}, {'name': '鸡丁饭', 'calorie': '85', 'probability': '0.00419035', 'baike_info': {}, 'has_calorie': True}], 'log_id': 1516250832939776876}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "菜品识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('菜品识别图.jpeg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload ={\n",
    "    'access_token':Sxylm_AI2,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    'top_num':5,\n",
    "    'filter_threshold':0.95\n",
    "} \n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.动物识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'result': [{'score': '0.549389', 'name': '美国短毛猫', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E7%BE%8E%E5%9B%BD%E7%9F%AD%E6%AF%9B%E7%8C%AB/300902', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/80cb39dbb6fd5266b5c16430a118972bd407362f', 'description': '美国短毛猫是原产于美国的一种猫，其祖先为欧洲早期移民带到北美的猫种，并与英国短毛猫,欧洲短毛猫同类。美国短毛猫的身体匀称、有力量，且活泼温顺。幼年短毛猫圆头圆脑，软绵绵的手感和灵活的四肢很是讨人喜欢。'}}, {'score': '0.121708', 'name': '家猫', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E5%AE%B6%E7%8C%AB/4200676', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/f9dcd100baa1cd11e6db6e9db112c8fcc3ce2d19', 'description': '家猫(学名：Felis catus)俗称猫咪，是食肉目猫科、猫属哺乳动物。平均体重约有3～4.5公斤左右，大多数全身披毛，毛皮毛色纷繁，全身横纹者居多，少量为纯一色或杂色者。趾底有脂肪质肉垫，趾端生有锐利的爪，爪平时不伸出，故行走无声。家猫为人类伴生动物之一。它猎食小鸟、兔子、老鼠、鱼等。在世界各地(除南极洲)都被发现与人类一起生活。家猫在世界自然保护联盟红色名录,华盛顿公约没有特殊的地位。(概述图来源)'}}, {'score': '0.0370164', 'name': '虎斑猫', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%99%8E%E6%96%91%E7%8C%AB/4972918', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/7af40ad162d9f2d323c5bdf1afec8a136227ccdc', 'description': '虎斑猫，原产美国。黄棕色的底色，夹有纯黑色的斑纹图案，且有一圈较浅的铜色呈环状包围。虎斑猫头部圆润，两耳间距较近，颈略短，肌肉发达。眼睛大而明亮，呈圆杏核状，颜色可以接受由黄色、金色至绿色，通常有眼线。鼻子是砖红色，有鼻线。毛型短而厚、质地生硬。个性独立、活泼、机警。捕鼠能力强。'}}, {'score': '0.0346996', 'name': '英国短毛猫', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E8%8B%B1%E5%9B%BD%E7%9F%AD%E6%AF%9B%E7%8C%AB/672846', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/8d5494eef01f3a292df5f01bf46fab315c6035a8d686', 'description': '英国短毛猫，体形圆胖，四肢粗短发达，毛短而密，头大脸圆，温柔平静，对人友善，极易饲养。大而圆的眼睛根据被毛不同而呈现各种颜色。作为一个古老的猫品种，其历史可追溯至古罗马时期的家猫，由于拥有悠久的育种历史，可以称得上是猫家族中的典范。英国短毛猫除了拥有固定耳距，代表性的遗传特征之外，又具有丰富的变异性，如背毛色眼睛颜色等。更重要的是，有了广泛的配种历史后，这种猫拥有了更健康的身体和更温驯的性格。'}}, {'score': '0.0265492', 'name': '欧洲短毛猫', 'baike_info': {'baike_url': 'http://baike.baidu.com/item/%E6%AC%A7%E6%B4%B2%E7%9F%AD%E6%AF%9B%E7%8C%AB/386735', 'image_url': 'https://bkimg.cdn.bcebos.com/pic/8326cffc1e178a82a153a044f603738da877e8e3', 'description': '欧洲短毛猫强壮耐劳，适应能力强。如乳黄色的淡色系往往很少。欧洲短毛猫远不如其英国或美国亲戚而闻名。在数似品种已建立稳固根基情况中，其很难说服培育者来发展这些短毛猫。乳黄色猫颜色的深度不一。暖色调带浅红色不讨人欢喜，而带有清晰虎纹猫同样也不讨人欢喜。然而这一种才有的缺陷很难克服，甚至同一窝猫仔颜色也是有深有浅。'}}, {'score': '0.0200865', 'name': '短毛猫'}], 'log_id': 1516250846326554014}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "动物识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v1/animal\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('动物识别图.jpeg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "payload ={\n",
    "    'access_token':Sxylm_AI2,\n",
    "    'image':img,\n",
    "    'baike_num':5,\n",
    "    'top_num':6\n",
    "} \n",
    "\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
